﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

using Mr.LinqToWeibo.SearchCriteria;
using System.Collections;

namespace Mr.LinqToWeibo
{
    public class WeiboContext
    {
        private IWeiboQueryService QueryService = new WeiboQueryServiceImpl();

        internal object Execute<T>(
            Expression expression,
            Scope scope,
            string accessToken,
            string accessTokenSecret,
            bool userObjectFilter)
        {
            if (!IsQueryOverDataSource(expression))
                throw new InvalidProgramException("No query over the data source was specified.");

            Type typeInScope = typeof(T);
            Type typeInQuery = TypeHelper.GetElementType(expression.Type);
            if (typeInScope != typeInQuery)
            {
                throw new InvalidProgramException("Type error, the target type is " + typeInScope + ", but " + typeInQuery + " in queryable expression.");
            }

            ISearchCriteria criteria = SearchCriteriaHelper.GetCriteria(expression);
            if (criteria != null)
            {
                this.QueryService.AccessToken = accessToken;
                this.QueryService.AccessTokenSecret = accessTokenSecret;

                object results = this.QueryService.GetObjects<T>(criteria, scope);

                if (results != null)
                {
                    if (userObjectFilter)
                    {
                        ExpressionTreeModifier<T> modifier = new ExpressionTreeModifier<T>(results);
                        results = modifier.GetFilterObjects(expression);
                    }
                    return results;
                }
            }

            throw new InvalidProgramException("Searching exception.");
        }

        private bool IsQueryOverDataSource(Expression expression)
        {
            return (expression is MethodCallExpression);
        }
    }
}

